const App = getApp()
import { PayModel } from '../../../models/pay.js'
import { AppModel } from '../../../models/app.js'
import { MineModel } from '../../../models/mine'
var pingpp = require('../../../utils/pingpp.js')
const ModelPay = new PayModel()
const appModel = new AppModel()
const mineModel = new MineModel()

Page({
  data: {
    ids: '',
    orderSource: 6, //1Android，2iOS，3PC，4H5，5接口，6小程序
    channel: 8, //支付渠道：1支付宝App支付，2支付宝扫码支付，3微信App支付，4微信公众号支付，5微信扫码支付，6余额支付，7智荟金桥，8微信小程序支付
    gold: null,
    addressId: '',
    paySuccess: false,
    userAddress: '',
    goodsNum: 0,
    goodsMoney: 0,
    freight: 0,
    availableGold: 0,
    userGold: 0,
    payAmount: 0,
    amount: 0,
    reliefMoney: 0,
    visible: false,
    goldRuleInfo: {},
    canUserGold: 0,
    leastUsedGold: 0,
    payDone: false,
    locked: false,
    inputGoldNumber: null,
    availableCouponNum: '',
    couponNum: 0,
    couponRange: 0,
    couponKey: '',
    couponAmount: '',
    statusBarHeight: App.globalData.statusBarHeight,
    isTabbar: false,
    orderType: 2, //	订单渠道来源：1小蚁买手，2小蚁买手，3专业代购
    showType: '',
    iphoneX: App.globalData.isIphoneX,
    userType: ''
  },
  onLoad: function(options) {
    // 第一次进入删除本地存储的地址id
    wx.removeStorageSync('addressId')
    this.data.ids = options.ids
  },
  onShow: function() {
    this.data.addressId = wx.getStorageSync('addressId')
    if (!this.data.payDone) {
      // 上锁，开始请求订单数据
      this.data.locked = true
      // 初始化数据
      this.getOrder()
    }
    // 如果已支付完成则不调用
    // if (!this.data.payDone) {
    //   // 获取地址
    //   this.data.addressId = App.WxService.getStorageSync('addressId')
    //   // 初始化数据
    //   this.initData()
    // }
  },
  // 获取订单数据
  getOrder() {
    const params = {
      cartId: this.data.ids.split(','),
      addressId: this.data.addressId,
      couponId: this.data.couponId
    }
    // 获取订单信息
    ModelPay.getPayOrder(params)
      .then(res => {
        // 解锁请求结束
        this.data.locked = false
        this.setData({
          userAddress: res.data.userAddress,
          goodsNum: res.data.goodsNum,
          goodsMoney: res.data.goodsMoney,
          freight: res.data.freight,
          userGold: res.data.userGold,
          availableGold: res.data.availableGold,
          payAmount: res.data.payAmount,
          amount: res.data.payAmount,
          reliefMoney: res.data.reliefMoney,
          leastUsedGold: res.data.leastUsedGold,
          availableCouponNum: res.data.availableCouponNum,
          couponNum: res.data.couponNum,
          couponKey: res.data.couponKey,
          couponAmount: res.data.couponAmount,
          couponRange: res.data.couponRange,
          userType: App.globalData.userInfo.userType
        })
        //如果使用了优惠券
        if (this.data.couponAmount > 0) {
          //判断应付金额
          if (
            this.data.payAmount <=
            this.data.freight + this.data.goodsNum * 1
          ) {
            this.setData({
              tipShow: true
            })
          }
        }
        // 如果已经输入了金额，那么就重置
        if (this.data.inputGoldNumber) {
          this.setData({
            payAmount: this.data.amount - this.data.inputGoldNumber
          })
        }
        // 如果有地址设置地址id
        if (res.data.userAddress) {
          this.data.addressId = res.data.userAddress.id
        }
      })
      .catch()
  },
  inputGold(e) {
    this.data.inputGoldNumber = e.detail.value
    //   let num= e.detail.value
    //this.data.payAmount可变 this.data.amount不可以变
    // 如果不是数字
    if (
      isNaN(this.data.inputGoldNumber) ||
      this.data.inputGoldNumber < 0 ||
      this.data.inputGoldNumber == ''
    ) {
      this.setData({
        gold: null,
        payAmount: this.data.amount,
        inputGoldNumber: null
      })
    } else if (this.data.inputGoldNumber > this.data.availableGold) {
      App.WxService.showToast({
        title: `最多可使用${this.data.availableGold}金币`,
        icon: 'none'
      })
      this.setData({
        gold: this.data.availableGold,
        payAmount: this.data.amount - this.data.availableGold,
        inputGoldNumber: this.data.availableGold
      })
      // 当可用金币大于最少使用金币
    } else if (
      this.data.availableGold > this.data.leastUsedGold &&
      this.data.inputGoldNumber < this.data.leastUsedGold
    ) {
      App.WxService.showToast({
        title: `最少可使用${this.data.leastUsedGold}金币`,
        icon: 'none'
      })
      this.setData({
        gold: this.data.leastUsedGold,
        payAmount: this.data.amount - this.data.leastUsedGold,
        inputGoldNumber: this.data.leastUsedGold
      })
    } else {
      // 如果金币不是整数倍
      let canuser = 0
      if (this.data.inputGoldNumber % 100 !== 0) {
        canuser = this.data.inputGoldNumber - this.data.inputGoldNumber % 100
        App.WxService.showToast({
          title: `只可使用100的整数倍金币`,
          icon: 'none',
          duration: 2000
        })
        this.setData({
          gold: canuser,
          payAmount: this.data.amount - canuser,
          inputGoldNumber: canuser
        })
      } else {
        this.setData({
          gold: e.detail.value,
          payAmount: this.data.amount - e.detail.value,
          inputGoldNumber: e.detail.value
        })
      }
    }
  },
  goPay(e) {
    // 如果还在请求数据就返回不让提交
    if (this.data.locked) {
      return
    }
    const that = this
    //保存formId
    const param = {
      formId: e.detail.formId
    }
    appModel
      .add_formId(param)
      .then(res => {})
      .catch()
    // 确认支付
    const params = {
      cartId: this.data.ids.split(','),
      gold: this.data.gold === null ? 0 : this.data.gold,
      amount: (this.data.payAmount / 100).toFixed(2),
      orderSource: this.data.orderSource,
      addressId: this.data.addressId,
      couponId: this.data.couponId,
      orderType: this.data.orderType
    }
    // 提交订单
    ModelPay.submitOrder(params)
      .then(res => {
        // 获取订单信息
        const payParams = {
          orderIds: res.data.orderIds,
          amount: (res.data.amount / 100).toFixed(2),
          channel: this.data.channel,
          open_id: App.globalData.userInfo.openId
        }
        // 调起支付
        ModelPay.pay(payParams)
          .then(res => {
            // loading
            wx.hideLoading()
            // ping++支付
            pingpp.createPayment(res.data.order, function(result, err) {
              if (result == 'success') {
                // 只有微信公众号 (wx_pub)、微信小程序（wx_lite）、QQ 公众号 (qpay_pub)支付成功的结果会在这里返回，其他的支付结果都会跳转到 extra 中对应的 URL
                // 查询支付结果
                // 设置已支付完成不刷新页面
                that.data.payDone = true
                that.getPayResult(res.data.pid)
              } else if (result == 'fail') {
                App.WxService.showToast({
                  title: '支付失败',
                  icon: 'none'
                })
                that.data.payDone = true
                // Ping++ 对象 object 不正确或者微信公众号/微信小程序/QQ公众号支付失败时会在此处返回
              } else if (result == 'cancel') {
                // 微信公众号、微信小程序、QQ 公众号支付取消支付
                App.WxService.showToast({
                  title: '取消支付',
                  icon: 'none'
                })
                that.data.payDone = true
                // 跳到了订单页
                App.WxService.redirectTo('/pages/account/order/list/index')
              }
            })
          })
          .catch(err => {
            // 跳到了订单页
            App.WxService.redirectTo('/pages/account/order/list/index')
          })
      })
      .catch(err => {
        console.log(err)
      })
  },
  getPayResult(pid) {
    setTimeout(function() {
      // 查询支付结果
      ModelPay.payResult({ pid: pid })
        .then(res => {
          if (res.status == 200) {
            App.WxService.redirectTo(
              '/packCart/pages/payOrder/success/index?pid=' + res.data.payCode
            )
           
          }
        })
        .catch(err => {
          App.WxService.redirectTo(
            '/packCart/pages/payOrder/success/index?pid=' + res.data.payCode
          )
        })
    }, 1000)
  },
  goAddress() {
    // 添加地址
    App.WxService.navigateTo(`/pages/account/address/address-edit/index`)
  },
  goAddressList() {
    // 列表地址
    App.WxService.navigateTo(`/pages/account/address/index`)
  },

  //选择优惠券
  selectCoupon() {
    //优惠券总数量大于0
    if (this.data.couponNum > 0) {
      if (this.data.coupon) {
        wx.navigateTo({
          url:
            '/pages/account/coupon/selectCoupon/index?couponKey=' +
            this.data.couponKey +
            '&couponId=' +
            this.data.coupon.id
        })
      } else {
        wx.navigateTo({
          url:
            '/pages/account/coupon/selectCoupon/index?couponKey=' +
            this.data.couponKey
        })
      }
    } else {
    }
  },

  connect() {
    // this.triggerEvent('emitservice')
    const params = {}
    const self = this
    ModelPay.queryGold(params)
      .then(res => {
        self.setData({
          goldRuleInfo: res.data.goldList[0]
        })
      })
      .catch()
    this.setData({
      visible: true
    })
  },

  closeGold() {
    this.setData({
      visible: false
    })
  },
  // 触发首页分享
  shareHome() {
    // 获取分享图
    mineModel.queryrule({ ruleType: '018' }).then(res => {
      // 图片以逗号分隔
      const homeShareImages = res.data.rule.ruleDetail.split(',')
      const userInfo = App.globalData.userInfo
      this.setData({
        showType: 'index',
        shareData: {
          showWay: 'nobar', // 不弹出底部分享
          shareTitle: ` ${decodeURIComponent(userInfo.nickName)} 邀您加入小蚁买手`,
          sharePath: `/pages/home/index?bossid=${userInfo.userCode}`,
          shareImg: homeShareImages[0],
          shareHomeImg: homeShareImages[1]
        }
      })
    })
  }
})
